<?php
/**
 * Created by PhpStorm.
 * User: 雨寒
 * Date: 2019/1/1
 * Time: 上午8:36
 */
namespace app\admin\controller;
include EXTEND_PATH."alipay/AopSdk.php";

use app\common\model\Order;
use think\Controller;
use think\Exception;
use think\Log;
use think\Db;
use think\Loader;
use app\common\model\WeixinPay;
use app\common\model\Message;
class PayNotify2 extends Common
{
    public function weixin()
    {
        Log::log(file_get_contents("php://input"));
        $xml = file_get_contents('php://input');//获取微信返回来的通知

        //file_put_contents('./1.txt', $xml,FILE_APPEND);
        $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);//解析数据

        if($arr=='')
        {
            $return = ['return_code'=>'FAIL','return_msg'=>'失败'];
        }else{

            if($arr['result_code']=="SUCCESS")
            {
                /*去掉其中的sign*/
                $old_sign=$arr['sign'];
                foreach ($arr as $k=>$v)
                {
                    if($k=='sign')
                    {
                        unset($arr[$k]);
                    }
                }

                $weixin=new WeixinPay();
                $sign=$weixin->getSign($arr);//根据返回的数据签名，和返回的签名比较是否一样

                //验签名。默认支持MD5
                if ( $sign === $old_sign) {
                    //file_put_contents('./1.txt', 'ceshi',FILE_APPEND);
                    //   校验返回的订单金额是否与商户侧的订单金额一致。修改订单表中的支付状态。
                    $order_info = db('partner_order')
                        ->where('order_sn', $arr['out_trade_no'])
                        ->find();
                    if($order_info&&$order_info['pay_status']==0){
                        //有此订单且未支付
                        $real_price = $order_info['money'];
                        $real_price = $real_price*100;
                        $real_price = intval($real_price);
                        if ($real_price != $arr['total_fee']) {

                            $return = ['return_code' => 'FAIL', 'return_msg' => '订单金额不对！'];
                            $this->wechat_return($return);
                        }
                        //保存支付状态
                        $change = [
                            'pay_status'=>1,
                            'pay_type'=>1,
                            'pay_sn'=>$arr['transaction_id'],
                            'pay_money'=>$arr['total_fee']/100,
                            'pay_time'=>now_datetime()
                        ];

                        $save = Db::name('partner_order')->where('id',$order_info['id'])->update($change);
                        if(!$save){
                            $return = ['return_code'=>'FAIL','return_msg'=>'保存失败'];
                            $this->wechat_return($return);
                        }

                        $user = Db::name('user')
                            ->where('id',$order_info['uid'])
                            ->find();
                        if($user&&$user['identity']<4){
                            $sa = Db::name('user')
                                ->where('id',$order_info['uid'])
                                ->update(['identity'=>4,'update_time'=>now_datetime()]);
                            if(!$sa){
                                throw new Exception('用户升级失败');
                            }
                        }

                    }

                    $return = ['return_code' => 'SUCCESS', 'return_msg' => 'OK'];
                }else{

                    $return = ['return_code'=>'FAIL','return_msg'=>'失败'];
                }
            }else{
                $return = ['return_code'=>'FAIL','return_msg'=>'失败'];
            }
        }

        $this->wechat_return($return);

    }

    public function wechat_return($return){
        $xml = '<xml>';
        foreach($return as $k=>$v){
            $xml.='<'.$k.'><![CDATA['.$v.']]></'.$k.'>';
        }
        $xml.='</xml>';

        echo $xml;die();
    }

    /*支付宝回调*/
    public function ali()
    {
        /*获取全部返回结果*/
        if(!empty($_POST))
        {
//            file_put_contents("return_data.txt",json_encode($_POST),FILE_APPEND);
            if($_POST['trade_status']!='TRADE_SUCCESS')
            {
                echo "fail";die;
            }else{
                /*订单信息*/
                $order_info = db('partner_order')
                    ->where('order_sn', $_POST['out_trade_no'])
                    ->find();


                if(empty($order_info)||($order_info['money']!=$_POST['total_amount']))
                {
                    echo "fail";die;
                }
                else
                {
                    if($order_info['pay_status']==1)
                    {
                        echo "success";die;
                    }

                    $aop=new \AopClient();
                    $aop->rsaPrivateKey = config('alipay.rsaPrivateKey') ;
                    $aop->alipayrsaPublicKey=config("alipay.alipayrsaPublicKey");

                    /*验签*/
                    $verify= $aop->rsaCheckV1($_POST, '','RSA2');

                    if(!$verify)
                    {
                        echo "fail";die;
                    }
                    //保存支付状态
                    $change = [
                        'pay_status'=>1,
                        'pay_type'=>1,
                        'pay_sn'=>$_POST['trade_no'],
                        'pay_money'=>$_POST['total_amount'],
                        'pay_time'=>now_datetime()
                    ];

                    $save = Db::name('partner_order')->where('id',$order_info['id'])->update($change);
                    if(!$save){
                        $return = ['return_code'=>'FAIL','return_msg'=>'保存失败'];
                        $this->wechat_return($return);
                    }

                    $user = Db::name('user')
                        ->where('id',$order_info['uid'])
                        ->find();
                    if($user&&$user['identity']<4){
                        $sa = Db::name('user')
                            ->where('id',$order_info['uid'])
                            ->update(['identity'=>4,'update_time'=>now_datetime()]);
                        if(!$sa){
                            throw new Exception('用户升级失败');
                        }
                    }

                    echo "success";
                }
            }
        }else{
            echo "fail";
        }
    }
}